package com.firefightingiot.firefightingiot.web.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.firefightingiot.firefightingiot.common.base.BaseService;
import com.firefightingiot.firefightingiot.model.DeviceBusiness;
import com.firefightingiot.firefightingiot.model.IpSoundFileName;
import com.firefightingiot.firefightingiot.model.IpSoundPlaying;
import com.firefightingiot.firefightingiot.model.IpSoundPlayingLoading;
import com.firefightingiot.firefightingiot.support.model.RespEntity;
import com.firefightingiot.firefightingiot.support.mybatisplus.QueryWrapper;
import com.firefightingiot.firefightingiot.support.utils.requestutil.HttpRequestUtil;
import com.firefightingiot.firefightingiot.web.mapper.DeviceBusinessMapper;
import com.firefightingiot.firefightingiot.web.mapper.IpSoundFileNameMapper;
import com.firefightingiot.firefightingiot.web.mapper.IpSoundPlayingLoadingMapper;
import com.firefightingiot.firefightingiot.web.mapper.IpSoundPlayingMapper;
import org.junit.Test;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class IPSoundColumnService extends BaseService {
    @Resource
    private UDPClient udpClient;
    @Resource
    private IPSoundColumnAsyncService ipSoundColumnAsyncService;
    @Resource
    private IpSoundFileNameMapper ipSoundFileNameMapper;
    @Resource
    private IpSoundPlayingMapper ipSoundPlayingMapper;
    @Resource
    private IpSoundPlayingLoadingMapper ipSoundPlayingLoadingMapper;
    @Resource
    private DeviceBusinessMapper deviceBusinessMapper;
    //UDPClient udpClient = new UDPClient();

    String headInit = "FEE0A7";
    String diD = "00001234";
    String cmd = "0F";

    //初始化头部
    public String initHeader(String diD, String cmd, String len0, String len1, String para) {
        diD = diD.substring(6, 8) + diD.substring(4, 6) + diD.substring(2, 4) + diD.substring(0, 2);
        String type = "8A";
        String sn = "0000";
        //帧头后的长度，小端
        //String para = "00";
        String accept = "00";
        //帧头算术和，取后两位
        String chkSum = "";
        String sum = makeChecksum(headInit + type + diD + sn + len0 + len1 + cmd + para + accept);
        int sumLength = sum.length();
        chkSum = sum.substring(sumLength - 2, sumLength);
        return headInit + type + diD + sn + len0 + len1 + cmd + para + accept + chkSum;
    }

    /**
     * 上传命令
     * @param diD
     * @param filePathString
     * @return
     */
    public RespEntity uploadMediaFile(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));

        //----------------- 检查该命令是否可执行
        String isplaySta = ipSoundPlayingLoadingState();
        if (!isplaySta.equals("0")) {
            return RespEntity.fail("中间件正在执行其他命令中，请于" + isplaySta + "再次执行");
        }
        //-----------------
        //初始化
        mv_state();
        //String diD = jsonParam.getStr("diD");
        //String number = jsonParam.getStr("number");
        String homeId = jsonParam.getStr("homeId");
        String id = jsonParam.getStr("id");
        String fileName = jsonParam.getStr("fileName");
        String filePathString = jsonParam.getStr("filePath");
        String cmd = "0F";
        String len0 = "";
        String len1 = "";
        String len = hex10To16(filePathString.length() + 2 + 1) + "";
        if (len.length() == 2) {
            len0 = len;
            len1 = "00";
        } else {
            len0 = len.substring(2, 4);
            len1 = len.substring(0, 2);
        }
        String header = initHeader(diD, cmd, len0, len1, "00");
        //保留
        String bo16 = "00";
        //保留
        String bo17 = "00";
        //第 18字节的值是字符串的长度
        String bo18 = "";
        //从第 19 字节开始为字符串，最长 255 个字节，文件路径字符串
        String filePath = stringToHexString(filePathString);
        String bo19 = filePath;
        bo18 = hex10To16(filePathString.length());
        String result = header + bo16 + bo17 + bo18 + bo19;
        System.out.println("result:" + result);
        try {
            //ArrayList arrayList = udpClient.startClient(result);
            JSONObject jsonParam1 = new JSONObject();
            jsonParam1.put("ss", result);
            RespEntity rest = rest(jsonParam1, "windowsServer", "startClient", "windowsServer", "POST");
            JSONObject data = (JSONObject)rest.getData();
            JSONArray arrayList = data.getJSONArray("data");
            if (arrayList.size() > 0) {
                for (Object o : arrayList) {
                    String reply = (String) o;
                    String cmdN = reply.substring(24, 26);
                    String paraN = reply.substring(36, 38);
                    //判断文件上传命令的应答帧是否包含文件编号id
                    if (cmdN.equals("85") && paraN.equals("02")) {
                        String fileNumber01 = reply.substring(48, 50);
                        String fileNumber02 = reply.substring(50, 52);
                        String fileNumber = fileNumber02 + fileNumber01;
                        String str1 = filePathString.substring(0, filePathString.indexOf("\\"));
                        String str2 = filePathString.substring(str1.length() + 1, filePathString.length());
                        System.out.println("uploadMediaFile:" + reply);
                        //查询原来数据
                        IpSoundFileName ipSoundFileNameOld = this.ipSoundFileNameMapper.selectById(id);
                        if (ipSoundFileNameOld != null && !ipSoundFileNameOld.equals("")) {
                            IpSoundFileName ipSoundFileName = new IpSoundFileName();
                            ipSoundFileName.setId(ipSoundFileNameOld.getId());
                            ipSoundFileName.setFilename(ipSoundFileNameOld.getFilename());
                            ipSoundFileName.setFilenumber(fileNumber.toUpperCase());
                            ipSoundFileName.setCreatetime(DateUtil.date());
                            //ipSoundFileName.setDevicenumber(number);
                            ipSoundFileName.setFilepath(ipSoundFileNameOld.getFilepath());
                            ipSoundFileName.setState("2");
                            ipSoundFileName.setHomeId(ipSoundFileNameOld.getHomeId());
                            this.ipSoundFileNameMapper.updateById(ipSoundFileName);
                        } else {
                            IpSoundFileName ipSoundFileName = new IpSoundFileName();
                            ipSoundFileName.setId(UUID.randomUUID().toString());
                            ipSoundFileName.setFilename(ipSoundFileNameOld.getFilename());
                            ipSoundFileName.setFilenumber(fileNumber.toUpperCase());
                            ipSoundFileName.setCreatetime(DateUtil.date());
                            //ipSoundFileName.setDevicenumber(number);
                            ipSoundFileName.setFilepath(ipSoundFileNameOld.getFilepath());
                            ipSoundFileName.setState("2");
                            ipSoundFileName.setHomeId(homeId);
                            this.ipSoundFileNameMapper.insert(ipSoundFileName);
                        }

                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespEntity.success();
    }

    /**
     * 删除文件（NAS 和 Windows）
     */
    public RespEntity deleteMediaFile(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        //----------------- 检查该命令是否可执行
        String isplaySta = ipSoundPlayingLoadingState();
        if (!isplaySta.equals("0")) {
            return RespEntity.fail("中间件正在执行其他命令中，请于" + isplaySta + "再次执行");
        }
        //-----------------
        String id = jsonParam.getStr("id");
        String newFileName = jsonParam.getStr("newFileName");
        String filePath = jsonParam.getStr("filePath");
        String fileNumber = jsonParam.getStr("fileNumber");
        //判断当前文件是否存在正在运行的任务，如果存在，则不允许停止
        List<IpSoundPlaying> playings = this.ipSoundPlayingMapper.selectList(new QueryWrapper<IpSoundPlaying>().eq("filenumber", fileNumber));
        if (playings.size() > 0) {
            IpSoundPlaying ipSoundPlaying = playings.get(0);
            if (DateUtil.date().compareTo(ipSoundPlaying.getEndtime()) < 0) {
                return RespEntity.fail(ipSoundPlaying.getFilename()+"存在正在运行的任务，无法删除！该任务结束时间："+DateUtil.format(ipSoundPlaying.getEndtime(),"yyyy-MM-dd HH:mm:ss"));
            }
        }
        String fileNumberReserve = fileNumber.substring(2, 4) + fileNumber.substring(0, 2);
        String stringLength = hex10To16(newFileName.length());;
        String cmd = "0E";
        String len0 = "";
        String len1 = "";
        String len = hex10To16(newFileName.length() + 2 + 1) + "";
        if (len.length() == 2) {
            len0 = len;
            len1 = "00";
        } else {
            len0 = len.substring(2, 4);
            len1 = len.substring(0, 2);
        }
        String para = "00";
        String filePathHex = stringToHexString(newFileName);
        String header = initHeader(diD, cmd, len0, len1, para);
        String body = fileNumberReserve + stringLength + filePathHex;
        String result = (header + body).toUpperCase();
        System.out.println("result: "+result);
        JSONObject jsonParam1 = new JSONObject();
        jsonParam1.put("ss", result);
        jsonParam1.put("filePath", filePath);
        if (id == null && id.equals("")) {
            return RespEntity.fail("该文件不存在！");
        }
        //删除NAS
        RespEntity rest = rest(jsonParam1, "windowsServer", "startClient", "windowsServer", "POST");
        JSONObject data = (JSONObject)rest.getData();
        //删除Windows服务器
        RespEntity rest2 = rest(jsonParam1, "windowsServer", "deleteServerFile", "windowsServer", "POST");
        //删除数据库
        this.ipSoundFileNameMapper.deleteById(id);

        return RespEntity.success();
    }
    @Test
    public void uploadTest() {
        DateTime date = DateUtil.date();
        String format = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss");
        System.out.println(format);
    }
    /**
     * 请求执行可编辑的播放任务
     * @return
     */
    public String requestEditableTask (String taskNumber,String timeMode, String timeType, String startTime, String entTime, String taskNameString,String playContentId, String playObjectId,int playNum) {
        //任务编号:可编辑任务00，定时任务FE taskNumber
        //String taskNumber = "00";
        //保留
        String baoLiuOne = "00";
        //任务类型: 0：文件播放 File,1：采播设备 Capture
        String taskType = "00";
        //定时类型和定时模式
        String timeTypeAndMode = "";
        //保留 timeTypeAndMode二进制
        String ttamBin7 = "0";
        String ttamBin6 = "0";
        //定时模式 Time Mode（起始时间的选项） ,01 绝对时间 Calendar,10 即时执行 Instant
        String ttamBin54 = "";
        //判断是否是可编辑任务或定时任务
        if (taskNumber.equals("00")) {
            if (timeMode.equals("Calendar")) {
                ttamBin54 = "01";
            } else if (timeMode.equals("Instant")) {
                ttamBin54 = "10";
            }
        } else if (taskNumber.equals("FE")) {
            if (timeMode.equals("WeekLoop")) {
                ttamBin54 = "00";
            } else if (timeMode.equals("Calendar")) {
                ttamBin54 = "01";
            }
        }

        String ttamBin32 = "00";
        //定时类型 Time Type（结束时间的选项）, 00 指定时刻 Time（结束时间无效） ,01 指定时段 Period
        String ttamBin10 = "";
        if (taskNumber.equals("00")) {
            if (timeType.equals("Time")) {
                ttamBin10 = "00";
            } else if (timeType.equals("Period")) {
                ttamBin10 = "01";
            }
        } else if (taskNumber.equals("FE")) {
            if (timeType.equals("Time")) {
                ttamBin10 = "00";
            } else if (timeType.equals("Period")) {
                ttamBin10 = "01";
            }
        }
        int i = Integer.parseInt(ttamBin7 + ttamBin6 + ttamBin54 + ttamBin32 + ttamBin10,2);
        timeTypeAndMode = hex10To16(i);
        //星期选项
        String week = "";
        if (taskNumber.equals("00")) {
            week = "00";
        } else if (taskNumber.equals("FE")) {
            //todo 周日-周一全天播放
            week = "FE";
        }
        //文件播放方式01循环播放，02顺序播放
        //String playbackMode = "01";
        //todo
        String playbackMode = "01";
        //播放内容的数量
        String playContentNumber = "02";
        //播放对象的数量
        //String playObjectNumber = "01";
        String playObjectNumber = "";
        String playNumHex = hex10To16(playNum);
        if (playNumHex.length() == 1) {
            playObjectNumber = "0" + playNumHex;
        } else {
            playObjectNumber = playNumHex;
        }
        //任务音量值任务的音量值，取值范围 0～127，单位-dB。0dB 是最大音量，值 127 对应-127dB 为最小音量。
        String taskVolume = "03";
        //提前打开功放时间
        String OpenAdvanceTime = "00";
        //保留2
        String baoLiuTwo = "00";
        //保留3
        String baoLiuThree = "00";
        //------------------------------------------------------------------------------
        //任务名称字符串
        int taskNameStringLength = taskNameString.length();
        String taskNameStringLengthString = "";
        if ((taskNameStringLength+"").length() == 1) {
            taskNameStringLengthString = "0" + taskNameStringLength;
        } else if ((taskNameStringLength+"").length() == 2) {
            taskNameStringLengthString = taskNameStringLength + "";
        }
        String taskName = stringToAscii(taskNameString).replace(",","");
        String heBing = taskNameStringLengthString + taskName;
        String ling = "";
        if (heBing.length() < 64) {
            int a = 64- heBing.length();
            for (int b = 0; b < a; b++) {
                ling += "0";
            }
        }
        taskNameString = heBing+ling;
        //播放内容编号表
        String playContent = playContentId;
        //播放目标编号表
        String playObject = playObjectId;
        String result = taskNumber + baoLiuOne + taskType + timeTypeAndMode + startTime + entTime + week + playbackMode + playContentNumber + playObjectNumber + taskVolume + OpenAdvanceTime + baoLiuTwo + baoLiuThree + taskNameString + playContent + playObject;
        System.out.println(result);
        return result;
    }

    /**
     * 下载媒体文件数据指令param=04
     * @param diD
     * @return
     */
    public String downLoadDataBy04(String diD){
        String header = initHeader(diD, "05", "00", "00","04");
        return header;
    }

    /**
     * 注册中间件
     * @param
     * @return
     */
    public RespEntity init(){
        //本地测试
        //String zhiling = "FEE0A78A00000000000034000100004434120000685634120A504C41594552B5D8C7F2000000000000000000000000000000000000000000C0A87701204E2B4E234E0000";
        //Windows服务器测试
        String zhiling = "FEE0A78A00000000000034000100004434120000685634120A504C41594552B5D8C7F2000000000000000000000000000000000000000000C0A8AA24204E2B4E234E0000";
        //测试
        //String zhiling = "FEE0A78A00000000000000000000000F";
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("ss", zhiling);
        //udpClient.startClient(zhiling);
        return rest(jsonParam, "windowsServer", "startClient", "windowsServer", "POST");


    }

    /**
     * 设置中间件状态，开启自动发送状态帧模式 2，状态变化时发送
     * @param
     * @return
     */
    public RespEntity mv_state(){
        String did1 = diD.substring(0, 2);
        String did2 = diD.substring(2, 4);
        String did3 = diD.substring(4, 6);
        String did4 = diD.substring(6, 8);
        String did = did4+did3+did2+did1;
        //String zhiling = "FEE0A78A"+did+"000000000402005B";
        String zhiling = "FEE0A78A34120000000000000402005B";
        //udpClient.startClient(zhiling);
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("ss", zhiling);
        return rest(jsonParam, "windowsServer", "startClient", "windowsServer", "POST");
    }

    //时间格式2021-09-29 00:02:00

    /**
     * 请求编辑执行任务
     * @param jsonParam
     * @return
     */
    public RespEntity publishAudioNew(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        //-----------------
        String isplaySta = ipSoundPlayingLoadingState();
        if (!isplaySta.equals("0")) {
            return RespEntity.fail("中间件正在执行其他命令中，请于" + isplaySta + "再次执行");
        }
        //-----------------
        String devNums = jsonParam.getStr("devicenumber");
        String[] split = devNums.split(",");
        for (String s : split) {
            List<IpSoundPlaying> devicenumberList = this.ipSoundPlayingMapper.selectList(new QueryWrapper<IpSoundPlaying>().eq("devicenumber", s));
            if (devicenumberList.size() > 0) {
                //音乐已经自己结束了
                if (DateUtil.date().compareTo(devicenumberList.get(0).getEndtime()) > 0) {
                    String id = devicenumberList.get(0).getId();
                    this.ipSoundPlayingMapper.deleteById(id);
                } else {
                    return RespEntity.fail("请先终止设备" + devicenumberList.get(0).getDevicenumber() + "播放");
                }
            }
        }
        ipSoundColumnAsyncService.publishAudio(jsonParam);
        Date endDate = DateUtil.offset(DateUtil.date(), DateField.SECOND,6);
        IpSoundPlayingLoading ipSoundPlayingLoading = new IpSoundPlayingLoading();
        ipSoundPlayingLoading.setId("123456");
        ipSoundPlayingLoading.setCreatetime(DateUtil.date());
        ipSoundPlayingLoading.setEndtime(endDate);
        this.ipSoundPlayingLoadingMapper.updateById(ipSoundPlayingLoading);
        return RespEntity.success();
    }

    /**
     * 请求编辑执行任务
     * @param jsonParam
     * @return
     */
    public RespEntity publishAudio(JSONObject jsonParam) {
        String devNums = jsonParam.getStr("devicenumber");
        String[] split = devNums.split(",");
        /*for (String s : split) {
            List<IpSoundPlaying> devicenumberList = this.ipSoundPlayingMapper.selectList(new QueryWrapper<IpSoundPlaying>().eq("devicenumber", s));
            if (devicenumberList.size() > 0) {
                //音乐已经自己结束了
                if (DateUtil.date().compareTo(devicenumberList.get(0).getEndtime()) > 0) {
                    String id = devicenumberList.get(0).getId();
                    this.ipSoundPlayingMapper.deleteById(id);
                } else {
                    return RespEntity.fail("请先终止设备" + devicenumberList.get(0).getDevicenumber() + "播放");
                }
            }
        }*/

        Object[] objects = splitAry(split, 200);
        for (Object o : objects) {
            String filename = "";
            String subId = "";
            String idResList = "";
            String[] ids = (String[]) o;
            for (String id : ids) {
                String idRes = id.substring(6, 8) + id.substring(4, 6) + id.substring(2, 4) + id.substring(0, 2);
                idResList += idRes;
            }
            String filenumberOld = jsonParam.getStr("filenumber");
            String filenumber = jsonParam.getStr("filenumber");
            String starttime = jsonParam.getStr("starttime");
            String endtime = jsonParam.getStr("endtime");
            //2021-09-29 00:02:00
            //2021-09-29 12:42:00
            //2021-09-29 20:02:00
            //定时任务
            String taskNumber = "00";
            String timeMode = "Calendar";
            String timeType = "Period";
            String startTime = getHexTime(starttime);
            String endTime = getHexTime(endtime);
            String taskNameString = "TASK6789";
            String filenumber01 = filenumber.substring(0, 2);
            String filenumber02 = filenumber.substring(2, 4);
            filenumber = filenumber02 + filenumber01;
            String playContentId = filenumber+"0000";
            String playObjectId = idResList;
            String date = requestEditableTask(taskNumber, timeMode, timeType, startTime, endTime, taskNameString, playContentId, playObjectId,ids.length);
            String len = hex10To16((date.length()) / 2);
            String len0 = "";
            String len1 = "";
            if (len.length() == 2) {
                len0 = len;
                len1 = "00";
            } else {
                len0 = len.substring(2, 4);
                len1 = len.substring(0, 2);
            }
            String header = initHeader(diD, "07", len0, len1, "00");
            String result = (header + date).toUpperCase();
            try {
                //ArrayList arrayList = udpClient.startClient(result);
                JSONObject jsonParam1 = new JSONObject();
                jsonParam1.put("ss", result);
                RespEntity rest = rest(jsonParam1, "windowsServer", "startClient", "windowsServer", "POST");
                JSONObject dataRest = (JSONObject)rest.getData();
                JSONArray arrayList = dataRest.getJSONArray("data");
            /*RespEntity rest = rest(jsonParam1, "windowsServer", "startClient", "windowsServer", "POST");
            ArrayList arrayList = (ArrayList)rest.getData();*/
                IpSoundFileName IpSoundFileName = this.ipSoundFileNameMapper.selectList(new QueryWrapper<IpSoundFileName>().eq("filenumber", filenumberOld)).get(0);
                filename = IpSoundFileName.getFilename();
                if (arrayList.size() > 0) {
                    String data = (String)arrayList.get(0);
                    String subIdReverse = data.substring(32, 40);
                    String subId1 = subIdReverse.substring(0, 2);
                    String subId2 = subIdReverse.substring(2, 4);
                    String subId3 = subIdReverse.substring(4, 6);
                    String subId4 = subIdReverse.substring(6, 8);
                    subId = subId4 + subId3 + subId2 + subId1;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            for (String id : ids) {
                IpSoundPlaying ipSoundPlaying = new IpSoundPlaying();
                ipSoundPlaying.setId(UUID.randomUUID().toString());
                ipSoundPlaying.setFilename(filename);
                ipSoundPlaying.setSubid(subId.toUpperCase());
                ipSoundPlaying.setSubid(subId.toUpperCase());
                ipSoundPlaying.setDevicenumber(id);
                ipSoundPlaying.setFilenumber(filenumberOld);
                ipSoundPlaying.setEndtime(DateUtil.parse(endtime));
                ipSoundPlayingMapper.insert(ipSoundPlaying);
            }
        }
        //*************************************************************************************************************************************************
        return RespEntity.success();
    }

    /**
     * 发布或播放列表
     * @param jsonParam
     * @return
     */
    public RespEntity publishOrPlayList(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String state = jsonParam.getStr("state");
        String homeId = jsonParam.getStr("homeId");
        List<IpSoundFileName> list = null;
        //state=1 为发布，state=2 为播放
        if (state.equals("1")) {
            list = this.ipSoundFileNameMapper.selectList(new QueryWrapper<IpSoundFileName>().eq("state", "1").eq("home_id", homeId));
        } else {
            list = this.ipSoundFileNameMapper.selectList(new QueryWrapper<IpSoundFileName>().eq("state", "2").eq("home_id", homeId));
        }
        return RespEntity.success(list);
    }

    /**
     * 终止播放
     * @param jsonParam
     * @return
     */
    public RespEntity endPlay(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        //----------------- 检查该命令是否可执行
        String isplaySta = ipSoundPlayingLoadingState();
        if (!isplaySta.equals("0")) {
            return RespEntity.fail("中间件正在执行其他命令中，请于" + isplaySta + "再次执行");
        }
        //-----------------
        String devicenumber = jsonParam.getStr("devicenumber");
        List<IpSoundPlaying> ipSoundPlayings = this.ipSoundPlayingMapper.selectList(new QueryWrapper<IpSoundPlaying>().eq("devicenumber", devicenumber));
        if (ipSoundPlayings.size() <= 0) {
            return RespEntity.fail("没有可以终止的任务");
        }
        //todo 如果查询条数大于1，则判断一下，删除
        IpSoundPlaying ipSoundPlaying = ipSoundPlayings.get(0);
        String id = ipSoundPlaying.getId();
        String subIdReserve = ipSoundPlaying.getSubid();
        String header = initHeader(diD, "0A", "04", "00", "00");
        String subId1 = subIdReserve.substring(0, 2);
        String subId2 = subIdReserve.substring(2, 4);
        String subId3 = subIdReserve.substring(4, 6);
        String subId4 = subIdReserve.substring(6, 8);
        String subId = subId4 + subId3 + subId2 + subId1;
        try {
            //udpClient.startClient(header + subId);
            JSONObject jsonParam1 = new JSONObject();
            jsonParam1.put("ss", header + subId);
            RespEntity rest = rest(jsonParam1, "windowsServer", "startClient", "windowsServer", "POST");
            this.ipSoundPlayingMapper.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespEntity.success();
    }

    /**
     * 批量终止播放
     * @param jsonParam
     * @return
     */
    public RespEntity endPlayAsyn(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        //----------------- 检查该命令是否可执行
        String isplaySta = ipSoundPlayingLoadingState();
        if (!isplaySta.equals("0")) {
            return RespEntity.fail("中间件正在执行其他命令中，请于" + isplaySta + "再次执行");
        }
        //-----------------
        /*List<IpSoundPlaying> ipSoundPlayings = this.ipSoundPlayingMapper.selectList(new QueryWrapper<IpSoundPlaying>().eq("devicenumber", devicenumber));
        if (ipSoundPlayings.size() <= 0) {
            return RespEntity.fail("没有可以终止的任务");
        }*/
        this.ipSoundColumnAsyncService.endPlay(jsonParam);

        String[] split = jsonParam.getStr("devicenumber").split(",");
        Date endDate = DateUtil.offset(DateUtil.date(), DateField.SECOND, split.length * 3);
        IpSoundPlayingLoading ipSoundPlayingLoading = new IpSoundPlayingLoading();
        ipSoundPlayingLoading.setId("123456");
        ipSoundPlayingLoading.setCreatetime(DateUtil.date());
        ipSoundPlayingLoading.setEndtime(endDate);
        this.ipSoundPlayingLoadingMapper.updateById(ipSoundPlayingLoading);
        return RespEntity.success();
    }

    /**
     * 获取 SubID 指定任务的实时运行信息命令
     * @param jsonParam
     * @return
     */
    public RespEntity getTaskRunInfo(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        //设备id
        String devicenumber = jsonParam.getStr("devicenumber");
        List<IpSoundPlaying> ipSoundPlayings = this.ipSoundPlayingMapper.selectList(new QueryWrapper<IpSoundPlaying>().eq("devicenumber", devicenumber));
        if (ipSoundPlayings.size() <= 0) {
            return RespEntity.fail("当前"+devicenumber+"没有正在播放的任务");
        } else {
            if (DateUtil.date().compareTo(ipSoundPlayings.get(0).getEndtime()) > 0) {
                return RespEntity.fail("当前"+devicenumber+"没有正在播放的任务");
            }
        }
        IpSoundPlaying ipSoundPlaying = ipSoundPlayings.get(0);
        String id = ipSoundPlaying.getId();
        String subIdReserve = ipSoundPlaying.getSubid();
        String header = initHeader(diD, "16", "04", "00", "00");
        String subId1 = subIdReserve.substring(0, 2);
        String subId2 = subIdReserve.substring(2, 4);
        String subId3 = subIdReserve.substring(4, 6);
        String subId4 = subIdReserve.substring(6, 8);
        String subId = subId4 + subId3 + subId2 + subId1;
        try {
            //ArrayList arrayList = udpClient.startClient(header + subId);
            JSONObject jsonParam1 = new JSONObject();
            jsonParam1.put("ss", header + subId);
            RespEntity rest = rest(jsonParam1, "windowsServer", "startClient", "windowsServer", "POST");
            JSONObject json = (JSONObject)rest.getData();
            JSONArray arrayList = json.getJSONArray("data");

            for (int i = 0; i < arrayList.size(); i++) {
                String data = (String)arrayList.get(i);
                int length = data.length();
                if (data.length()>40 && data.toUpperCase().substring(24, 26).equals("8D")) {
                    String subIdNewReserve = data.substring(40, 48);
                    String subIdNew1 = subIdNewReserve.substring(0, 2);
                    String subIdNew2 = subIdNewReserve.substring(2, 4);
                    String subIdNew3 = subIdNewReserve.substring(4, 6);
                    String subIdNew4 = subIdNewReserve.substring(6, 8);
                    String subIdNew = (subIdNew4 + subIdNew3 + subIdNew2 + subIdNew1).toUpperCase();

                    IpSoundPlaying playingInfo = this.ipSoundPlayingMapper.selectList(new QueryWrapper<IpSoundPlaying>().eq("subid", subIdNew)).get(0);
                    return RespEntity.success(playingInfo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespEntity.success("未获取到文件");
    }

    /**
     * 设置 SubID 指定的任务音量命令 SetTaskVolume
     * @param jsonParam
     * @return
     */
    public RespEntity SetTaskVolume(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        //设备id
        String devicenumber = jsonParam.getStr("devicenumber");
        List<IpSoundPlaying> ipSoundPlayings = this.ipSoundPlayingMapper.selectList(new QueryWrapper<IpSoundPlaying>().eq("devicenumber", devicenumber));
        if (ipSoundPlayings.size() <= 0) {
            return RespEntity.fail("当前没有正在播放的任务");
        }
        IpSoundPlaying ipSoundPlaying = ipSoundPlayings.get(0);
        String id = ipSoundPlaying.getId();
        String subIdReserve = ipSoundPlaying.getSubid();
        String header = initHeader(diD, "16", "04", "00", "00");
        String subId1 = subIdReserve.substring(0, 2);
        String subId2 = subIdReserve.substring(2, 4);
        String subId3 = subIdReserve.substring(4, 6);
        String subId4 = subIdReserve.substring(6, 8);
        String subId = subId4 + subId3 + subId2 + subId1;
        try {
            //ArrayList arrayList = udpClient.startClient(header + subId);
            JSONObject jsonParam1 = new JSONObject();
            jsonParam1.put("ss", header + subId);
            RespEntity rest = rest(jsonParam1, "windowsServer", "startClient", "windowsServer", "POST");
            JSONObject json = (JSONObject)rest.getData();
            JSONArray arrayList = json.getJSONArray("data");

            for (int i = 0; i < arrayList.size(); i++) {
                String data = (String)arrayList.get(i);
                int length = data.length();
                if (data.length()>40 && data.toUpperCase().substring(24, 26).equals("8D")) {
                    String subIdNewReserve = data.substring(40, 48);
                    String subIdNew1 = subIdNewReserve.substring(0, 2);
                    String subIdNew2 = subIdNewReserve.substring(2, 4);
                    String subIdNew3 = subIdNewReserve.substring(4, 6);
                    String subIdNew4 = subIdNewReserve.substring(6, 8);
                    String subIdNew = (subIdNew4 + subIdNew3 + subIdNew2 + subIdNew1).toUpperCase();

                    IpSoundPlaying playingInfo = this.ipSoundPlayingMapper.selectList(new QueryWrapper<IpSoundPlaying>().eq("subid", subIdNew)).get(0);
                    return RespEntity.success(playingInfo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespEntity.success("未获取到文件");
    }

    public RespEntity setTaskVolumeNew(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        //----------------- 检查该命令是否可执行
        String isplaySta = ipSoundPlayingLoadingState();
        if (!isplaySta.equals("0")) {
            return RespEntity.fail("中间件正在执行其他命令中，请于" + isplaySta + "再次执行");
        }
        //-----------------
        this.ipSoundColumnAsyncService.SetPlayerVolume(jsonParam);

        String[] split = jsonParam.getStr("deviceNumber").split(",");
        Date endDate = DateUtil.offset(DateUtil.date(), DateField.SECOND, split.length * 3);
        IpSoundPlayingLoading ipSoundPlayingLoading = new IpSoundPlayingLoading();
        ipSoundPlayingLoading.setId("123456");
        ipSoundPlayingLoading.setCreatetime(DateUtil.date());
        ipSoundPlayingLoading.setEndtime(endDate);
        this.ipSoundPlayingLoadingMapper.updateById(ipSoundPlayingLoading);
        for (String id : split) {
            DeviceBusiness deviceBusiness = new DeviceBusiness();
            deviceBusiness.setLedVolume(jsonParam.getStr("vol"));
            deviceBusinessMapper.update(deviceBusiness, new QueryWrapper<DeviceBusiness>().eq("number", id));
        }
        return RespEntity.success();
    }


    /**
     * 获取设备音量，并显示设备音量
     * @param jsonParam
     * @return
     */
    public RespEntity showDeviceVolume(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        String deviceNumber = jsonParam.getStr("deviceNumber");
        if (deviceNumber != null && !deviceNumber.equals("")) {
            List<DeviceBusiness> list = this.deviceBusinessMapper.selectList(new QueryWrapper<DeviceBusiness>().eq("number", deviceNumber));
            if (list.size() > 0) {
                return RespEntity.success(list.get(0));
            }
        }
        return RespEntity.fail("该设备不存在！");
    }

    public RespEntity setTaskVolume(JSONObject jsonParam) {
        //处理支持form-data和json两种方式
        jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        //调用token验证接口
        com.alibaba.fastjson.JSONObject token = makeDataForToken(jsonParam, "systemsetup", "config", "getDecodeToken", "systemsetup");
        if (StrUtil.isNotBlank(token.getString("methodCodeFlag"))) return RespEntity.expire();
        if (StrUtil.isNotBlank(token.getString("methodErrorFlag"))) return RespEntity.fail(token.getString("msg"));
        //----------------- 检查该命令是否可执行
        String isplaySta = ipSoundPlayingLoadingState();
        if (!isplaySta.equals("0")) {
            return RespEntity.fail("中间件正在执行其他命令中，请于" + isplaySta + "再次执行");
        }
        //-----------------
        String deviceNumber = jsonParam.getStr("deviceNumber");
        List<IpSoundPlaying> list = this.ipSoundPlayingMapper.selectList(new QueryWrapper<IpSoundPlaying>().eq("devicenumber", deviceNumber));
        if (list.size() <= 0) {
            return RespEntity.fail("该设备下没有正在播放的任务");
        }
        String subId = list.get(0).getSubid();
        //0～127
        int vol = jsonParam.getInt("vol");
        String volHex = hex10To16(vol);
        String header = initHeader(diD, "0B", "08", "00", "00");
        String body = subId.substring(6, 8) + subId.substring(4, 6) + subId.substring(2, 4) + subId.substring(0, 2) + volHex + "000000";
        JSONObject jsonParam1 = new JSONObject();
        jsonParam1.put("ss", header + body);
        RespEntity rest = rest(jsonParam1, "windowsServer", "startClient", "windowsServer", "POST");
        JSONObject json = (JSONObject)rest.getData();
        JSONArray arrayList = json.getJSONArray("data");
        return RespEntity.success();
    }

    /**
     * 文件媒体数据解析
     * @param data 该data包含数据头部信息和数据参数信息
     * @return
     */
    public ArrayList<JSONObject> fileMediaDataAnalysis(String data){
        //数据头
        String header = data.substring(0, 32);
        String len0 = header.substring(20, 22);
        String len1 = header.substring(22, 24);
        String len = len1 + len0;
        //16进制字符串转10进制数字
        int lenNum = Integer.parseInt(len, 16)*2;
        //截取的params
        String params = data.substring(32);
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add(params.substring(0, 272));
        arrayList.add(params.substring(272, 272*2));
        arrayList.add(params.substring(272*2, 272*3));
        arrayList.add(params.substring(272*3, 272*4));
        arrayList.add(params.substring(272*4, 272*5));
        arrayList.add(params.substring(272*5, 272*6));
        arrayList.add(params.substring(272*6, 272*7));
        arrayList.add(params.substring(272*7, 272*8));
        arrayList.add(params.substring(272*8, 272*9));
        arrayList.add(params.substring(272*9, lenNum));

        //解析完，并组长最终数据
        ArrayList<JSONObject> list = new ArrayList<>();
        for (String param : arrayList) {
            JSONObject jsonObject = new JSONObject();
            String fileId01 = param.substring(0, 2);
            String fileId02 = param.substring(2, 4);
            String fileId = fileId02 + fileId01;
            //fileNameAll = 文件名长度+文件名
            String fileNameAll = param.substring(16);
            int fileNameSize = Integer.parseInt(fileNameAll.substring(0, 2),16);
            String fileNameHex =  fileNameAll.substring(2, 2+fileNameSize*2);
            //十六进制转字符串
            String fileName = HexStringToBytes(fileNameHex);
            jsonObject.put("fileId", fileId);
            jsonObject.put("fileName", fileName);
            list.add(jsonObject);
        }
        return list;
    }

    /**
     * 用于检查当前中间件是否处于空闲状态
     * @return
     */
    public String ipSoundPlayingLoadingState(){
        List<IpSoundPlayingLoading> list = this.ipSoundPlayingLoadingMapper.selectList(new QueryWrapper<IpSoundPlayingLoading>().eq("id", "123456"));
        //有数据的时候
        if (list.size() > 0) {
            IpSoundPlayingLoading ipSoundPlayingLoading = list.get(0);
            Date endtime = ipSoundPlayingLoading.getEndtime();
            //结束了
            if (DateUtil.date().compareTo(endtime) > 0) {
                return "0";
            } else {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy.MM.dd-HH:mm:ss");
                String dateString = simpleDateFormat.format(endtime);
                return dateString;
            }

        } else {
            return "0";
        }
    }


    public static String hex10To16(int valueTen){
        String s = Integer.toHexString(valueTen);
        if (s.length() == 1) {
            return "0"+Integer.toHexString(valueTen);
        } else {
            return Integer.toHexString(valueTen);
        }
    }


    public static String makeChecksum(String hexdata) {
        if (hexdata == null || hexdata.equals("")) {
            return "00";
        }
        hexdata = hexdata.replaceAll(" ", "");
        int total = 0;
        int len = hexdata.length();
        if (len % 2 != 0) {
            return "00";
        }
        int num = 0;
        while (num < len) {
            String s = hexdata.substring(num, num + 2);
            total += Integer.parseInt(s, 16);
            num = num + 2;
        }
        return hexInt(total);
    }

    private static String hexInt(int total) {
        int a = total / 256;
        int b = total % 256;
        if (a > 255) {
            return hexInt(a) + format(b);
        }
        return format(a) + format(b);
    }

    private static String format(int hex) {
        String hexa = Integer.toHexString(hex);
        int len = hexa.length();
        if (len < 2) {
            hexa = "0" + hexa;
        }
        return hexa;
    }

    /**
     * 字符串转换为16进制字符串
     *
     * @param s
     * @return
     */
    public static String stringToHexString(String s) {
        String str = "";
        for (int i = 0; i < s.length(); i++) {
            int ch = (int) s.charAt(i);
            String s4 = Integer.toHexString(ch);
            str = str + s4;
        }
        return str;
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将字符串转成ASCII方法
     * @param value
     * @return
     */
    public static String stringToAscii(String value)
    {
        StringBuffer sbu = new StringBuffer();
        char[] chars = value.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if(i != chars.length - 1)
            {
                sbu.append(hex10To16((int)chars[i]));
            }
            else {
                sbu.append(hex10To16((int)chars[i]));
            }
        }
        return sbu.toString().toUpperCase();
    }


    // 转化十六进制编码为字符串(中文乱码已解决)从十六进制字符串到字节数组转换
    public static String HexStringToBytes(String hexstr) {
        byte[] b = new byte[hexstr.length() / 2];
        int j = 0;
        for (int i = 0; i < b.length; i++) {
            char c0 = hexstr.charAt(j++);
            char c1 = hexstr.charAt(j++);
            b[i] = (byte) ((parse(c0) << 4) | parse(c1));
        }
        String store_name = "";
        try {
            store_name  = new String(b,"GB2312");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return store_name;
    }
    // 转化十六进制编码为字符串(中文乱码已解决)从十六进制字符串到字节数组转换
    private static int parse(char c) {
        if (c >= 'a')
            return (c - 'a' + 10) & 0x0f;
        if (c >= 'A')
            return (c - 'A' + 10) & 0x0f;
        return (c - '0') & 0x0f;
    }


    /**
     * 10进制时间转16进制时间
     * @param time
     * @return
     */
    public String getHexTime(String time) {

        //20210929000200
        String time0 = time.replace("-", "");
        String time1 = time0.replace(":", "");
        String time2 = time1.replace(" ", "");
        String year = time2.substring(2, 4);
        String month = time2.substring(4, 6);
        String day = time2.substring(6, 8);
        String hour = time2.substring(8, 10);
        String minute = time2.substring(10, 12);
        String second = time2.substring(12, 14);

        String yearHex = hex10To16(Integer.parseInt(year));
        String monthHex = hex10To16(Integer.parseInt(month));
        String dayHex = hex10To16(Integer.parseInt(day));
        String hourHex = hex10To16(Integer.parseInt(hour));
        String minuteHex = hex10To16(Integer.parseInt(minute));
        String secondHex = hex10To16(Integer.parseInt(second));
        return (yearHex + monthHex + dayHex + hourHex + minuteHex + secondHex).toUpperCase();

    }

    /**
     * splitAry方法<br>
     * @param ary 要分割的数组
     * @param subSize 分割的块大小
     * @return
     *
     */
    private static Object[] splitAry(String[] ary, int subSize) {
        int count = ary.length % subSize == 0 ? ary.length / subSize: ary.length / subSize + 1;

        List<List<String>> subAryList = new ArrayList<List<String>>();

        for (int i = 0; i < count; i++) {
            int index = i * subSize;
            List<String> list = new ArrayList<>();
            int j = 0;
            while (j < subSize && index < ary.length) {
                list.add(ary[index++]);
                j++;
            }
            subAryList.add(list);
        }

        Object[] subAry = new Object[subAryList.size()];

        for(int i = 0; i < subAryList.size(); i++){
            List<String> subList = subAryList.get(i);
            String[] subAryItem = new String[subList.size()];
            for(int j = 0; j < subList.size(); j++){
                subAryItem[j] = subList.get(j);
            }
            subAry[i] = subAryItem;
        }

        return subAry;
    }
}
